package com.packagetracker.helpers;

import java.util.LinkedList;

import android.app.Activity;
import android.database.Cursor;
import android.net.Uri;

import com.packagetracker.entities.TrackingNumber;
import com.packagetracker.providers.TrackerProviderSetup;

public class NumbersHelper {
	
	private Activity activity;
	
	public NumbersHelper(final Activity activity) {
		this.activity = activity;
	}
	
	public LinkedList<TrackingNumber> getNumbers() {
		final LinkedList<TrackingNumber> numbers = new LinkedList<TrackingNumber>();
		final Cursor cursor = this.activity.getContentResolver().query(TrackerProviderSetup.Numbers.NUMBERS_URI, this.getProjection(), null, null, null);
		if (cursor != null) {
			while (cursor.moveToNext()) {
				numbers.addFirst(this.fillNumber(cursor));
			}
		}
		
		cursor.close();
		
		return numbers;
	}
	
	public TrackingNumber getNumber(final String trackingNumber) {
		final Cursor cursor = this.activity.getContentResolver().query(Uri.parse("content://" + TrackerProviderSetup.URI + "/" + TrackerProviderSetup.Numbers.TABLE_NAME + "/" + trackingNumber), this.getProjection(), null, null, null);
		if ((cursor != null) && cursor.moveToNext()) {
			return this.fillNumber(cursor);
		}
		
		return null;
	}
	
	private String[] getProjection() {
		return new String[] {
				TrackerProviderSetup.Numbers._ID,
				TrackerProviderSetup.Numbers.CARRIER,
				TrackerProviderSetup.Numbers.NUMBER };
	}
	
	private TrackingNumber fillNumber(final Cursor cursor) {
		final TrackingNumber number = new TrackingNumber();
		number.setId(cursor.getInt(cursor.getColumnIndex(TrackerProviderSetup.Numbers._ID)));
		number.setCarrier(cursor.getInt(cursor.getColumnIndex(TrackerProviderSetup.Numbers.CARRIER)));
		number.setNumber(cursor.getString(cursor.getColumnIndex(TrackerProviderSetup.Numbers.NUMBER)));
		
		return number;
	}
	
}